import { computed } from "vue-demi";
import baseStore from "@/store/modules/base";
import { message } from "ant-design-vue";
import permissionStore from "@/store/modules/permission";
// import { getBlobByPathApi, signFileUploadApi } from "@/api/common/file";
// import { GeneraDataType } from "@/interface";
import { useRoute } from "vue-router";
import { cloneDeep } from "lodash";
import * as XLSX from "xlsx";
import axios from "axios";
export default function CommonHook() {
  const route = useRoute();
  // 常量数据字典
  const dataDict = computed(() => {
    return baseStore.dataDict;
  });
  // fileType MIME映射
  const MIME: { [propsName: string]: any } = {
    doc: "application/msword",
    docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    csv: "text/csv",
    gif: "image/gif",
    jpeg: "image/jpeg",
    jpg: "image/jpeg",
    png: "image/png",
    pdf: "application/pdf",
    pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    zip: "application/zip"
  };
  // 过滤
  const getLabelByDict = (key: string, val: any) => {
    const target = dataDict.value[key] || [];
    const { name } = target.find((t: any) => t.code === String(val)) || {};
    return name || "-";
  };
  // 根据下载链接 自定义文件名 下载文件
  const downloadFileByUrl = (url: string, filename = "模板.xlsx", type = "application/vnd.ms-excel") => {
    axios(url, { responseType: "blob" }).then((res: any) => {
      if (res.status === 200) {
        downloadFileByBlob(res.data, filename, type);
      }
    });
  };
  // blob 流下载
  const downloadFileByBlob = (res: Blob, filename = "模板.xlsx", type = "application/vnd.ms-excel") => {
    const blob = new Blob([res], { type });
    const objectUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    document.body.appendChild(a);
    a.setAttribute("style", "display:none");
    a.setAttribute("href", objectUrl);
    a.setAttribute("download", filename);
    a.click();
    URL.revokeObjectURL(objectUrl);
    message.success("下载成功!");
  };
  // 单文件上传
  // const signFileUpload = (file: File, params?: GeneraDataType, callBack?: (state: any) => void) => {
  //   const formData = new FormData();
  //   formData.append("file", file);
  //   return signFileUploadApi(formData, params).then((res: any) => {
  //     const { code, data } = res;
  //     if (code === 0) {
  //       message.success("上传成功!");
  //       callBack && callBack(data);
  //     } else {
  //       message.error("上传失败");
  //     }
  //     return res;
  //   });
  // };
  // // 根据URL 获取 Blob 下载文件
  // const downloadFileByUrlToBlob = (row: GeneraDataType) => {
  //   getBlobByPathApi({ path: row.path }).then((res: any) => {
  //     downloadFileByBlob(res, row.sysFileName);
  //   });
  // };
  // 匹配中文
  const zhReg = /[\u4E00-\u9FA5]/g;
  // 判断是否有权限
  const hasPermission = (code: string) => {
    const path = route.path;
    const targetPagePermissionMap = permissionStore.permissionMap;
    if (targetPagePermissionMap[path] && targetPagePermissionMap[path].btnAuth) {
      if (targetPagePermissionMap[path].btnAuth.includes(code)) return true;
    }
    return false;
  };
  // 将内容复制到剪切板
  const copyText = (content: string) => {
    try {
      const aux = document.createElement("textarea");
      aux.value = content;
      document.body.appendChild(aux);
      aux.select();
      document.execCommand("copy");
      document.body.removeChild(aux);
      message.success("复制成功!");
    } catch (err) {
      message.error("复制失败!" + err);
    }
  };
  // 转换为树形结构
  const convertToTree = (array: Array<Base.GeneraDataType>, baseKey: string | number = "id", relevanceKey: string | number = "pid") => {
    const temp: Base.GeneraDataType = {};
    const tree: Base.GeneraDataType = {};
    const result: Array<Base.GeneraDataType> = [];
    for (const i in array) {
      temp[array[i][baseKey]] = array[i];
    }
    for (const i in temp) {
      if (temp[i][relevanceKey] && String(temp[i][relevanceKey]) !== "0") {
        if (temp[temp[i][relevanceKey]]) {
          if (!temp[temp[i][relevanceKey]].child) temp[temp[i][relevanceKey]].child = [temp[i]];
          else temp[temp[i][relevanceKey]].child.push(temp[i]);
        }
        // if (temp[temp[i][relevanceKey]] && !temp[temp[i][relevanceKey]].child) {
        //   temp[temp[i][relevanceKey]].child = [temp[i]];
        // }
        temp[temp[i][relevanceKey]].child.push(temp[i]);
      } else {
        tree[temp[i][baseKey]] = temp[i];
      }
    }
    for (const key in tree) {
      result.push(tree[key]);
    }
    return result;
  };
  // 扁平化
  const flattening = (array: Array<Base.GeneraDataType>, result: Array<Base.GeneraDataType> = [], key: string | number = "child") => {
    for (let i = 0; i < array.length; i++) {
      const target = array[i];
      const data = cloneDeep(target);
      Reflect.deleteProperty(data, `${key}`);
      result.push(data);
      if (target[key] && target[key].length) flattening(target[key], result);
    }
    return result;
  };
  // 根据某个字段进行分类 （单层结构）
  const getClassifyArrayByFields = (array: Array<Base.GeneraDataType>, field: string, disabledFiled?: string) => {
    const result = [],
      map = new Map();
    for (let i = 0; i < array.length; i++) {
      const target = array[i];
      if (map.get(target[field])) {
        const source = map.get(target[field]);
        source.push({
          label: target.channelName,
          value: target.id,
          disabled: disabledFiled ? (target[disabledFiled] ? true : false) : false,
          ...target
        });
      } else {
        map.set(target[field], [
          {
            label: target.channelName,
            value: target.id,
            disabled: disabledFiled ? (target[disabledFiled] ? true : false) : false,
            ...target
          }
        ]);
      }
    }
    for (const val of map) {
      result.push({
        label: getLabelByDict("CHANNEL_ALLOCATION", val[0]),
        value: val[0],
        children: val[1]
      });
    }
    return result;
  };
  // 获取 类数组 中 第一个 键值 不为 0 的 键名
  const getNoZeroKey = (target: { [propsName: string]: number }, keys: string[]) => {
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      if (Number(target[key])) return key;
    }
    return keys[0];
  };
  // 将JSON数据导出 excel
  const exportJsonToExcel = (excelHeader: Array<Array<string>>, data: Array<Base.GeneraDataType>, fileName: string) => {
    const headerWs = XLSX.utils.aoa_to_sheet(excelHeader);
    const ws = XLSX.utils.sheet_add_json(headerWs, data, { skipHeader: true, origin: "A2" });
    /* 新建空的工作表 */
    const wb = XLSX.utils.book_new();

    // 可以自定义下载之后的sheetname
    XLSX.utils.book_append_sheet(wb, ws, "sheetName");

    /* 生成xlsx文件 */
    XLSX.writeFile(wb, `${fileName}.xlsx`);
  };
  // 判断是否是数组
  const isArray = (target: any) => {
    return Object.prototype.toString.call(target) === "[object Array]";
  };
  // JSON序列化
  const stringify = (target: any) => {
    return JSON.stringify(target, (key: string, val: any) => {
      if (typeof val === "function") return `FUN_FLAG${val}`;
      else return val;
    });
  };
  // JSON.parse 改造
  const parse = (target: string) => {
    return JSON.parse(target, (key: string, val: any) => {
      if (val && typeof val === "string") {
        return val.includes("FUN_FLAG") ? new Function(`return ${val.replace("FUN_FLAG", "")}`)() : val;
      } else return val;
    });
  };
  return {
    dataDict,
    getLabelByDict,
    downloadFileByBlob,
    downloadFileByUrl,
    // signFileUpload,
    // downloadFileByUrlToBlob,
    hasPermission,
    zhReg,
    copyText,
    MIME,
    convertToTree,
    flattening,
    getClassifyArrayByFields,
    getNoZeroKey,
    exportJsonToExcel,
    isArray,
    stringify,
    parse
  };
}
